package com.jinyang.jetpackdemo.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.jinyang.jetpackdemo.R
import com.jinyang.jetpackdemo.util.LjyLogUtil
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.core.app.NotificationManagerCompat


class MyServiceForeground : Service() {


    override fun onCreate() {
        super.onCreate()
        LjyLogUtil.d("MyServiceForeground.onCreate:${Thread.currentThread().name}")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        LjyLogUtil.d("MyServiceForeground.onStartCommand: intent=$intent _ flags=$flags _ startId=$startId")
        createNotificationChannel()
//        silentForegroundNotification()
        GlobalScope.launch {
            repeat(20) {
                LjyLogUtil.d("${Thread.currentThread().name}_job:$it")
                delay(1000)
            }
            stopSelf()
        }
        return super.onStartCommand(intent, flags, startId)

    }

    private fun silentForegroundNotification() {
        val channelId = "my_channel_01"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelName = "我的隐藏通知名字"
            val channel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            channel.lockscreenVisibility = Notification.VISIBILITY_SECRET //设置在锁屏界面上显示这条通知

            channel.description = "我的隐藏通知描述"
            channel.lightColor = Color.GREEN
            channel.setSound(null, null)
            channel.enableVibration(false)
            val builder: NotificationCompat.Builder =
                NotificationCompat.Builder(this, channelId)
            builder.setContentTitle("")
            builder.setContentText("")
            builder.setDefaults(Notification.DEFAULT_ALL)
            builder.setAutoCancel(true)
            builder.setShowWhen(true)
            builder.setSmallIcon(R.drawable.ic_launcher_foreground)

            // 这里两个通知使用同一个id且必须按照这个顺序后调用startForeground
            val notificationId = 111
            NotificationManagerCompat.from(this).notify(notificationId, builder.build())
            startForeground(notificationId, builder.build())
        }
    }

    private fun createNotificationChannel() {
        val mNotificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // 通知渠道的id
        val channelId = "my_channel_01"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 用户可以看到的通知渠道的名字.
            val name = "我的前台服务通知渠道名字"
            // 用户可以看到的通知渠道的描述
            val description = "我的前台服务通知渠道描述"
            val importance: Int = NotificationManager.IMPORTANCE_HIGH
            val mChannel = NotificationChannel(channelId, name, importance)
            // 配置通知渠道的属性
            mChannel.description = description
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true)
            mChannel.lightColor = Color.RED
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true)
            mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            // 最后在notificationmanager中创建该通知渠道 //
            mNotificationManager.createNotificationChannel(mChannel)
        }

        // Create a notification and set the notification channel.
        val notification: Notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder(this, channelId)
                .setContentTitle("消息title").setContentText("You've received new messages.")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build()
        } else {
            Notification.Builder(this)
                .setContentTitle("消息title").setContentText("You've received new messages.")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build()
        }
        val notificationId = 111
        startForeground(notificationId, notification)
    }


    override fun onDestroy() {
        super.onDestroy()
        stopForeground(true)
        LjyLogUtil.d("MyServiceForeground.onDestroy")
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

}